import { Footer } from '@/components';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import {InfoCircleOutlined, LockOutlined, MobileOutlined, SafetyOutlined, UserOutlined} from '@ant-design/icons';
import { LoginForm, ProFormCaptcha, ProFormText } from '@ant-design/pro-components';
import { history, useModel, Helmet } from '@umijs/max';
import {Alert, Col, Divider, Form, message, Row, Tabs, Tooltip} from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, {useEffect, useState} from 'react';
import { createStyles } from 'antd-style';
import { userRegisterUsingPost } from '@/services/api-share-backhend/userController';
import {Link} from "@@/exports";

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

const Lang = () => {
  const { styles } = useStyles();
  return;
};
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};
const Register: React.FC = () => {
  const [userLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { styles } = useStyles();

  useEffect(() => {
    console.log("register")
  }, []);
  const handleSubmit = async (values) => {
    if(type==="mobile"){
      message.info("系统暂未开通此功能，敬请期待！")
    }
    else {
      try {
        // 注册 todo 放到后端
        if(values.authorization!=="maktoub"){
          message.error("授权码错误")
        }
        else{
          const res = await userRegisterUsingPost({
            ...values,
          });
          if (res.data !== null) {
            message.success('注册成功');
            const urlParams = new URL(window.location.href).searchParams;
            history.push(urlParams.get('redirect') || '/');
            return;
          } else {
            const msg = res.message;
            message.error(msg);
          }
        }
        // 如果失败去设置用户错误信息
        // setUserLoginState(msg);
      } catch (error) {
        const defaultLoginFailureMessage = '注册失败，请重试！';
        message.error(defaultLoginFailureMessage);
      }
    }
  };
  const [form] = Form.useForm();

  const { status, type: loginType } = userLoginState;
  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'注册'}- {Settings.title}
        </title>
      </Helmet>
      <Lang />
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
            key={"register"}
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          submitter={{
            searchConfig: {
              submitText: '注册',
            },
          }}
          formRef={form}
          logo={<img alt="logo" src="/favicon.ico" />}
          title="api共享枢纽平台"
          subTitle={'汇集多个API，提供一站式接口服务。'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.UserRegisterRequest);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码注册',
              },
              {
                key: 'mobile',
                label: '手机号注册',
              },
            ]}
          />

          {status === 'error' && loginType === 'account' && <LoginMessage content={'注册失败'} />}
          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'请输入用户名'}
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                  {
                    min: 2,
                    max: 18,
                    message: '用户名长度为2-18!',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                  {
                    min: 6,
                    message: '密码长度最少为6位！',
                  },
                ]}
              />{' '}
              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'确认密码'}
                rules={[
                  {
                    required: true,
                    message: '请再次输入密码！',
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('userPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('前后密码不一致'));
                    },
                  }),
                ]}
              />

              <Row align="middle">
                <Col lg={21}>
                  <ProFormText
                      name={"authorization"}
                      fieldProps={{
                        size: 'large',
                        prefix: <SafetyOutlined />,
                      }}
                      captchaProps={{
                        size: 'large',
                      }}
                      placeholder={'填写授权码'}
                      rules={[
                        {
                          required: true,
                          message: '请填写授权码！',
                        }
                      ]}
                  />
                </Col>
                <Col>
                  <Tooltip title="授权码由管理员提供，没有授权码的用户暂时无法注册">
                    <InfoCircleOutlined style={{ fontSize: '22px', marginLeft: '8px',marginBottom:20, color: '#1890ff' }} />
                  </Tooltip>
                </Col>
              </Row>
            </>
          )}

          {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="mobile"
                placeholder={'手机号'}
                rules={[
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '手机号格式错误！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'秒后重新获取'}`;
                  }
                  return '获取验证码';
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: '请输入验证码！',
                  },
                ]}
                onGetCaptcha={async (phone) => {
                  const result = await getFakeCaptcha({
                    phone,
                  });
                  if (!result) {
                    return;
                  }
                  message.success('获取验证码成功！验证码为：1234');
                }}
              />
            </>
          )}
          <Divider
              style={{
                margin: '0px 0px',
              }}
          />
          <Link
              style={{
                float: 'right',
                marginBottom: '5px',
              }}
              to={'/user/login'}
          >
            已有账号？前往登录
          </Link>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Register;
